<?php

namespace app\common\model;

use think\Model;
use think\Exception;
/**
 * Trade
 */
class Trade extends Model
{
    // 表名
    protected $name = 'trade';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected static function onBeforeInsert($model): void
    {
        $user = User::where('id', $model->user_id)->find();
        if (!$user) {
            throw new Exception("The user can't find it");
        }
        if (!$model->reamrk) {
            throw new Exception("Change note cannot be blank");
        }
        $pk         = $model->getPk();
        $model->$pk = \app\common\library\SnowFlake::generateParticle();
        if($model->trade_type == 'recharge'){
            if($model->type = 'wechat'){
                $model->before = $user->balance;
                $user->balance += $model->balance;
                $user->save();
                $model->after = $user->balance;
            }
            if($model->type = 'gift'){
                $model->before = $user->balance_zs;
                $user->balance_zs += $model->balance;
                $user->save();
                $model->after = $user->balance_zs;
            }
        }
        if($model->trade_type == 'expense'){
            if($model->type = 'wechat'){
                $model->before = $user->balance;
                $user->balance -= $model->balance;
                $user->save();
                $model->after = $user->balance;
            }
            if($model->type = 'gift'){
                $model->before = $user->balance_zs;
                $user->balance_zs -= $model->balance;
                $user->save();
                $model->after = $user->balance_zs;
            }
        }
    }


    public function getIdAttr($value): string
    {
        return (string)$value;
    }

    public function getBeforeBalanceAttr($value): ?float
    {
        return is_null($value) ? null : (float)$value;
    }

    public function getBalanceAttr($value): ?float
    {
        return is_null($value) ? null : (float)$value;
    }
    

    public function getAfterBalanceAttr($value): ?float
    {
        return is_null($value) ? null : (float)$value;
    }

    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\User::class, 'user_id', 'id');
    }
}